<template>
  <div>
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <van-cell-group>
      <van-cell v-for="(item, index) in showList" :key="index" icon="search"
      @click="$router.push({path:'/searchResult',query:{q:list[index]}})"
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 4.搜索历史 -->
    <van-cell-group>
      <van-cell title="历史记录"> </van-cell>
      <van-cell title="单元格">
        <van-icon name="close" />
      </van-cell>
      <van-cell title="单元格">
        <van-icon name="close" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestionList } from './home.js'
export default {
  name: 'search',
  data () {
    return {
      value: '',
      list: [],
      timeID: null
    }
  },
  methods: {
    onSearch () {
      console.log(this.value)
      this.$router.push({ path: '/searchResult', query: { q: this.value } })
    },
    onInput () {
      clearTimeout(this.timeID)
      this.timeID = setTimeout(async () => {
        if (!this.value) {
          this.list = []
          return
        }
        let res = await getSuggestionList(this.value)
        //  console.log(res);
        this.list = res.data.data.options
      }, 500)
    }
  },
  computed: {
    showList () {
      const reg = new RegExp(this.value, 'gi')
      return this.list.map(item => {
        return item.replace(reg, match => {
          return `<span style="color:red">${match}</span>`
        })
      })
    }
  }
}
</script>

<style></style>
